package com.pocketsweet.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.avos.avoscloud.AVCloud;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.FunctionCallback;
import com.avos.avoscloud.RefreshCallback;
import com.avos.avoscloud.SaveCallback;
import com.easemob.EMCallBack;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMMessage;
import com.easemob.chat.TextMessageBody;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.pocketsweet.C;
import com.pocketsweet.R;
import com.pocketsweet.chat.ui.activity.BaseActivity;
import com.pocketsweet.chat.ui.activity.ChatActivity;
import com.pocketsweet.model.MLGift;
import com.pocketsweet.model.MLGiftRecord;
import com.pocketsweet.model.MLUser;
import com.pocketsweet.service.UserService;
import com.pocketsweet.ui.uilib.AutoListView;
import com.pocketsweet.ui.uilib.AutoListView.OnLoadListener;
import com.pocketsweet.ui.uilib.AutoListView.OnRefreshListener;
import com.pocketsweet.ui.uilib.HeaderLayout;
import com.pocketsweet.ui.uilib.HeaderLayout.HeaderStyle;
import com.pocketsweet.ui.uilib.HeaderLayout.onLeftContainerListener;
import com.pocketsweet.ui.uilib.LoadingDailog;
import com.pocketsweet.ui.uilib.SendGiftDialog;
import com.pocketsweet.ui.uilib.adapter.GiftStoreAdapter;
import com.pocketsweet.utils.ToolKits;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@ContentView(R.layout.activity_gift_store)
public class GiftStore extends BaseActivity implements OnRefreshListener,
        OnLoadListener, OnItemClickListener {

    @ViewInject(R.id.giftListview)
    private static AutoListView giftListview;

    @ViewInject(R.id.mainHeader)
    private static HeaderLayout header;

    @ViewInject(R.id.linBlank)
    private static LinearLayout linBlank;

    @ViewInject(R.id.tvBlankBg)
    private static TextView tvBlankBg;

    @ViewInject(R.id.tvBlankNoLove)
    private static TextView tvBlankNoLove;

    public static LoadingDailog loading;
    private GiftStoreAdapter giftRecordAdapter;
    private List<MLGift> giftStoreList = new ArrayList<MLGift>();
    private Context ctx;
    public static final int BEGIN_TO_LOADING = -1;
    private int skipDataCount = 0; // 忽略前N个对象
    public static final int MORE_DATA_MAX_COUNT = 25; // 每页10个对象
    private boolean isUpdateList = false; // 是否刷新列表
    private String toUserId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ViewUtils.inject(this);
        ctx = this;
        giftRecordAdapter = new GiftStoreAdapter(GiftStore.this, giftStoreList);
        giftListview = (AutoListView) findViewById(R.id.giftListview);
        header = (HeaderLayout) findViewById(R.id.mainHeader);
        linBlank = (LinearLayout) findViewById(R.id.linBlank);
        giftListview.setAdapter(giftRecordAdapter);
        giftListview.setPageSize(MORE_DATA_MAX_COUNT);
        giftListview.setOnRefreshListener(this);
        giftListview.setOnLoadListener(this);
        giftListview.setOnItemClickListener(this);
        setHeaderFunction();
        getFollowedList(AutoListView.REFRESH);
    }

    public void setHeaderFunction() {
        header = (HeaderLayout) findViewById(R.id.mainHeader);
        header.init(HeaderStyle.IMG_TITLE_TEXT);
        header.setRightText("");
        String nickName = getIntent().getStringExtra("nickName");
        toUserId = getIntent().getStringExtra("toUserId");
        header.setMiddleText("送" + nickName + "的礼物");
        header.setLeftContainerClickListener(new onLeftContainerListener() {

            @Override
            public void onClick() {
                GiftStore.this.finish();
            }
        });
    }

    private void getFollowedList(final int what) {
        loading = ToolKits.createLoadingDialog(GiftStore.this, "提交中..");
        loading.setText("正在获取中");
        linBlank.setVisibility(View.GONE);
        if (what != BEGIN_TO_LOADING) {
            isUpdateList = true; // 如果不是首次加载数据，则该动作为刷新
        } else {
            giftListview.setRefreshData(); // 初始化显示loading动态图片
        }
        if (giftStoreList == null || giftStoreList.size() <= 0 || isUpdateList) { // userList为空或者动作为下拉刷新、往下加载时请求leanCloud

            AVQuery<MLGift> querys = new AVQuery<MLGift>("MLGift");
            skipDataCount = skipDataCount + MORE_DATA_MAX_COUNT; // 往下加载时忽略前一页
            if (what != AutoListView.LOAD) {
                skipDataCount = 0; // 刷新时不用忽略前面对象
            }
            querys.orderByAscending("priority");
            querys.setSkip(skipDataCount); // 忽略前N个
            querys.limit(MORE_DATA_MAX_COUNT); // 设置每页对象个数
            querys.findInBackground(new FindCallback<MLGift>() {

                @Override
                public void done(List<MLGift> records, AVException e) {
                    if (e == null) {
                        if (records.size() > 0) {
                            linBlank.setVisibility(View.GONE);
                            switch (what) {
                                case AutoListView.REFRESH: // 下拉刷新时直接重新获取数据
                                    giftStoreList = records;
                                    giftListview.onRefreshComplete();
                                    // onLineListAdapter.setDatas(userList);
                                    break;
                                case AutoListView.LOAD: // 加载更多时把新获取的数据添加到list列表
                                    giftListview.onLoadComplete();
                                    giftStoreList.addAll(records);
                                    break;
                                case BEGIN_TO_LOADING: // Application无数据时首次加载，即重新获取数据
                                    giftStoreList = records;
                                    giftListview.onRefreshComplete();
                                    // onLineListAdapter.setDatas(userList);
                                    break;
                            }
                            giftListview.setResultSize(giftStoreList.size());
                            giftRecordAdapter.setDatas(giftStoreList);
                            giftRecordAdapter.notifyDataSetChanged();
                            isUpdateList = false; // 刷新完毕，设为false
                        } else if (records.size() == 0) {
                            linBlank.setVisibility(View.VISIBLE);
                            if (what != AutoListView.LOAD) {
                                tvBlankBg
                                        .setBackgroundResource(R.drawable.no_follower);
                                tvBlankNoLove.setText(getResources().getString(
                                        R.string.blank_no_gift));
                                linBlank.setVisibility(View.VISIBLE);
                            }
                            giftListview.setNoData();
                        }
                    } else {
                        giftListview.setNoData();
                        if (giftStoreList.size() <= 0) {
                            linBlank.setVisibility(View.VISIBLE);
                            tvBlankBg
                                    .setBackgroundResource(R.drawable.network_error);
                            tvBlankNoLove.setText(getResources().getString(
                                    R.string.blank_network_error));
                            linBlank.setOnClickListener(new OnClickListener() {

                                @Override
                                public void onClick(View arg0) {
                                    getFollowedList(BEGIN_TO_LOADING);
                                }
                            });
                        } else {
                            ToolKits.toast(GiftStore.this, "网络错误");
                        }
                    }
                }

            });
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {
        if (position - 1 < 0 || giftRecordAdapter.getCount() <= 0) {
            return;
        }
        final MLGift mlGift = (MLGift) giftRecordAdapter
                .getItem(position - 1);
        final SendGiftDialog dialog = new SendGiftDialog(GiftStore.this)
                .builder().setTitle(mlGift.getName())
                .setGiftImg(mlGift.getImgUrl())
                .setPrice(String.valueOf((int) mlGift.getPrice()) + "时光")
                .setInfo(mlGift.getInfo())
                .setTitle(mlGift.getName()).setNegativeButton("取消", new OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                });
        dialog.setPositiveButton("赠送", new OnClickListener() {
            @Override
            public void onClick(View v) {//赠送礼物
                UserService.getCurrentUser().refreshInBackground(new RefreshCallback<AVObject>() {
                    @Override
                    public void done(AVObject avObject, AVException e) {
                        if (e == null) {
                            double balance = UserService.getCurrentUser().getBalance();
                            if (balance >= (float) (mlGift.getPrice() / 10)) {
                                MLGiftRecord mlGiftRecord = new MLGiftRecord();
                                MLUser mlUser = new MLUser();
                                MLUser toUser = new MLUser();
                                mlUser.setObjectId(UserService.getCurrentUserId());
                                toUser.setObjectId(toUserId);
                                mlGiftRecord.setUser(mlUser);
                                mlGiftRecord.setReceiver(toUser);
                                mlGiftRecord.setGift(mlGift);
                                mlGiftRecord.saveInBackground(new SaveCallback() {
                                    @Override
                                    public void done(AVException e) {
                                        if (e == null) {
                                            ToolKits.toast(GiftStore.this, "礼物赠送成功");
//                                            Intent mIntent = new Intent();
//                                            mIntent.putExtra("giftName", mlGift.getName());
//                                            mIntent.putExtra("giftInfo", mlGift.getInfo());
//                                            mIntent.putExtra("giftImg", mlGift.getImgUrl());
                                            // 设置结果，并进行传送
//                                            GiftStore.this.setResult(RESULT_OK, mIntent);
                                            double balance = UserService.getCurrentUser().getBalance();
                                            balance = balance - (float) mlGift.getPrice() / 10;
                                            BigDecimal balanceFormat = new BigDecimal(
                                                    balance)
                                                    .setScale(
                                                            2,
                                                            BigDecimal.ROUND_HALF_UP);
                                            balance = balanceFormat
                                                    .doubleValue();
                                            UserService.getCurrentUser().setBalance(balance);
                                            UserService.getCurrentUser().saveInBackground();
                                            double price = (float) mlGift.getPrice() * 0.07;//提成7成
                                            // 调用云代码给对方钱
                                            Map<String, Object> params = new HashMap<String, Object>();
                                            params.put(
                                                    "userId",
                                                    toUserId);
                                            params.put(
                                                    "price",
                                                    price);
                                            AVCloud.callFunctionInBackground(
                                                    "newTransferAccount",
                                                    params,
                                                    new FunctionCallback<String>() {

                                                        @Override
                                                        public void done(
                                                                String arg0,
                                                                AVException arg1) {//给对方发送口袋君消息
                                                            int price = (int) (mlGift.getPrice() * 0.7);
                                                            String msg = UserService.getCurrentUser().getNickname() + "送你礼物“"
                                                                    + mlGift.getName() + "”，已兑换成" + String.valueOf(price) + "时光存进你的钱包";
                                                            Map<String, Object> params1 = new HashMap<String, Object>();
                                                            params1.put("touserId", toUserId);
                                                            params1.put("msg",
                                                                    msg);
                                                            AVCloud.callFunctionInBackground("sendSysMsg", params1, null);

                                                            EMConversation conversation = EMChatManager
                                                                    .getInstance()
                                                                    .getConversation(
                                                                            UserService.getCurrentUser()
                                                                                    .getObjectId());
                                                            EMMessage message = EMMessage
                                                                    .createSendMessage(EMMessage.Type.TXT);
                                                            String content = "送你一个礼物”" + mlGift.getName() + "”";
                                                            TextMessageBody txtBody = new TextMessageBody(content);
                                                            message.setAttribute("giftType", C.EMMESSAGE_EXT_TYPE_GIFT_MSG);
                                                            message.setAttribute("giftImg", mlGift.getImgUrl());
                                                            message.setAttribute("giftName", mlGift.getName());
                                                            message.setAttribute("giftInfo", mlGift.getInfo());

                                                            // 设置消息body
                                                            message.addBody(txtBody);
                                                            // 设置要发给谁,用户username或者群聊groupid
                                                            message.setReceipt(toUserId);
                                                            // 把messgage加到conversation中
                                                            // 发送消息
                                                            EMChatManager
                                                                    .getInstance()
                                                                    .sendMessage(
                                                                            message, null);
                                                        }
                                                    });
                                        } else {
                                            ToolKits.toast(GiftStore.this, "赠送失败");
                                        }
                                    }
                                });
                            } else {
                                ToolKits.toast(GiftStore.this, "时光不足，请充值");
                            }
                        }
                    }
                });

            }
        });
        dialog.show();
    }

    @Override
    public void onLoad() {
        getFollowedList(AutoListView.LOAD);

    }

    @Override
    public void onRefresh() {
        getFollowedList(AutoListView.REFRESH);
        giftListview.setOnRefreshListener(this);

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
    }

}
